package com.xjy.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.xjy.common.exception.CustomException;
import com.xjy.common.exception.UtilException;
import com.xjy.common.utils.PageUtils;
import com.xjy.common.core.page.PagePlus;
import com.xjy.common.core.page.TableDataInfo;
import com.xjy.system.domain.SysCreditAdvance;
import com.xjy.system.domain.SysLoan;
import com.xjy.system.domain.bo.*;
import com.xjy.system.domain.vo.SysCreditAdvanceVo;
import com.xjy.system.domain.vo.SysLoanVo;
import com.xjy.system.mapper.SysCreditAdvanceMapper;
import com.xjy.system.mapper.SysLoanMapper;
import com.xjy.system.service.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xjy.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjy.system.domain.SysReimbursement;
import com.xjy.system.mapper.SysReimbursementMapper;
import com.xjy.system.domain.vo.SysReimbursementVo;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 费用报销信息Service业务层处理
 *
 * @author xjy
 * @date 2022-02-10
 */
@Service
public class SysReimbursementServiceImpl extends ServicePlusImpl<SysReimbursementMapper, SysReimbursement> implements ISysReimbursementService {

	@Autowired
	private ISysFundaccountdetailService iSysFundaccountdetailService;
	@Autowired
	private ISysCheckaccountService iSysCheckaccountService;

	@Autowired
	private SysLoanMapper sysLoanMapper;
	@Autowired
	private ISysLoanService iSysLoanService;
	@Autowired
	private SysCreditAdvanceMapper sysCreditAdvanceMapper;
	@Autowired
	private ISysCreditAdvanceService iSysCreditAdvanceService;


    @Override
    public SysReimbursementVo queryById(Long id){
		SysReimbursementVo rsp =  getVoById(id, SysReimbursementVo.class);
		rsp.setLoanList(new ArrayList<>());
		rsp.setAdvanceList(new ArrayList<>());
		//支付类别:0：支付报销，1：冲销借款，2：冲销预付
		Integer payType = rsp.getPayType();
		if(payType == 1 || payType == 3){
			SysLoanQueryBo sysLoanQueryBo = new SysLoanQueryBo();
			sysLoanQueryBo.setResultContractNoCharge(rsp.getReimbursementNo());
			List<SysLoanVo> sysLoanVoList = sysLoanMapper.queryList(sysLoanQueryBo);
			List<SysLoanChargeBo> loanList = BeanUtil.copyToList(sysLoanVoList,SysLoanChargeBo.class);
			if(null != loanList){
				rsp.setLoanList(loanList);
			}
		}
		if(payType == 2	|| payType == 3){
			SysCreditAdvanceQueryBo sysCreditAdvanceQueryBo = new SysCreditAdvanceQueryBo();
			sysCreditAdvanceQueryBo.setAdvanceNoCharge(rsp.getReimbursementNo());
			List<SysCreditAdvanceVo> sysCreditAdvanceVoList = sysCreditAdvanceMapper.queryList(sysCreditAdvanceQueryBo);
			List<SysCreditAdvanceChargeBo> advanceList = BeanUtil.copyToList(sysCreditAdvanceVoList,SysCreditAdvanceChargeBo.class);
			if(null != advanceList){
				rsp.setAdvanceList(advanceList);
			}
		}
        return rsp;
    }

    @Override
    public TableDataInfo<SysReimbursementVo> queryPageList(SysReimbursementQueryBo bo) {
        PagePlus<SysReimbursement, SysReimbursementVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), SysReimbursementVo.class);
        List<SysReimbursementVo> rows = result.getRecordsVo();
        if(rows.size() > 0){
			List<String> reimbursementNoList = rows.stream().map(SysReimbursementVo::getReimbursementNo).collect(Collectors.toList());
			SysLoanQueryBo sysLoanQueryBo = new SysLoanQueryBo();
			sysLoanQueryBo.setResultContractNoChargeList(reimbursementNoList);
			List<SysLoanVo> sysLoanVoList = sysLoanMapper.queryList(sysLoanQueryBo);
			List<SysLoanChargeBo> loanList = BeanUtil.copyToList(sysLoanVoList,SysLoanChargeBo.class);
			Map<String,List<SysLoanChargeBo>> loanListMaps = loanList.stream().collect(Collectors.groupingBy(SysLoanChargeBo::getResultContractNoCharge));



			SysCreditAdvanceQueryBo sysCreditAdvanceQueryBo = new SysCreditAdvanceQueryBo();
			sysCreditAdvanceQueryBo.setAdvanceNoChargeList(reimbursementNoList);
			List<SysCreditAdvanceVo> sysCreditAdvanceVoList = sysCreditAdvanceMapper.queryList(sysCreditAdvanceQueryBo);
			List<SysCreditAdvanceChargeBo> advanceList = BeanUtil.copyToList(sysCreditAdvanceVoList,SysCreditAdvanceChargeBo.class);
			Map<String,List<SysCreditAdvanceChargeBo>> advanceListMasp = advanceList.stream().collect(Collectors.groupingBy(SysCreditAdvanceChargeBo::getAdvanceNoCharge));

			for(SysReimbursementVo sysReimbursementVo:rows){
				List<SysLoanChargeBo> loans = null == loanListMaps.get(sysReimbursementVo.getReimbursementNo())? new ArrayList<>():loanListMaps.get(sysReimbursementVo.getReimbursementNo());
				List<SysCreditAdvanceChargeBo> advances = null == advanceListMasp.get(sysReimbursementVo.getReimbursementNo())? new ArrayList<>():advanceListMasp.get(sysReimbursementVo.getReimbursementNo());
				sysReimbursementVo.setLoanList(loans);
				sysReimbursementVo.setAdvanceList(advances);
			}
			result.setRecordsVo(rows);
		}


		return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<SysReimbursementVo> queryList(SysReimbursementQueryBo bo) {
        return listVo(buildQueryWrapper(bo), SysReimbursementVo.class);
    }

    private LambdaQueryWrapper<SysReimbursement> buildQueryWrapper(SysReimbursementQueryBo bo) {

        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysReimbursement> lqw = Wrappers.lambdaQuery();
		lqw.in(null != bo.getIdList() && bo.getIdList().size() >0, SysReimbursement::getId, bo.getIdList());
        lqw.eq(bo.getProjId() != null, SysReimbursement::getProjId, bo.getProjId());
        lqw.eq(bo.getContractId() != null, SysReimbursement::getContractId, bo.getContractId());
        lqw.eq(bo.getResultProjId() != null, SysReimbursement::getResultProjId, bo.getResultProjId());
        lqw.eq(StrUtil.isNotBlank(bo.getReimbursementNo()), SysReimbursement::getReimbursementNo, bo.getReimbursementNo());

		lqw.eq(bo.getBudgetId() != null, SysReimbursement::getBudgetId, bo.getBudgetId());
        lqw.eq(StrUtil.isNotBlank(bo.getAffiliatedUnit()), SysReimbursement::getAffiliatedUnit, bo.getAffiliatedUnit());
        lqw.eq(bo.getAffiliatedUnitId() != null, SysReimbursement::getAffiliatedUnitId, bo.getAffiliatedUnitId());
        lqw.eq(StrUtil.isNotBlank(bo.getAffiliatedPerson()), SysReimbursement::getAffiliatedPerson, bo.getAffiliatedPerson());
        lqw.eq(bo.getAffiliatedPersonId() != null, SysReimbursement::getAffiliatedPersonId, bo.getAffiliatedPersonId());
        lqw.eq(StrUtil.isNotBlank(bo.getHandler()), SysReimbursement::getHandler, bo.getHandler());
        lqw.eq(bo.getHandlerId() != null, SysReimbursement::getHandlerId, bo.getHandlerId());

        lqw.eq(bo.getAgencyLogo() != null, SysReimbursement::getAgencyLogo, bo.getAgencyLogo());
        lqw.eq(StrUtil.isNotBlank(bo.getExpenseDept()), SysReimbursement::getExpenseDept, bo.getExpenseDept());
        lqw.eq(StrUtil.isNotBlank(bo.getAbstracted()), SysReimbursement::getAbstracted, bo.getAbstracted());
        lqw.eq(bo.getReimbAmt() != null, SysReimbursement::getReimbAmt, bo.getReimbAmt());
        lqw.eq(bo.getInvoiceNum() != null, SysReimbursement::getInvoiceNum, bo.getInvoiceNum());
        lqw.eq(StrUtil.isNotBlank(bo.getImage()), SysReimbursement::getImage, bo.getImage());
		lqw.eq(bo.getUploadTime() != null, SysReimbursement::getUploadTime, bo.getUploadTime());
		lqw.like(StrUtil.isNotBlank(bo.getAffiliatedPerson()), SysReimbursement::getAffiliatedPerson, bo.getAffiliatedPerson());
		lqw.eq(bo.getPayType() != null, SysReimbursement::getPayType, bo.getPayType());
        return lqw;
    }

    @Transactional
    @Override
    public Boolean insertByAddBo(SysReimbursementChargeBo bo) {
    	if(null != bo.getContractId()){
    		if(null == bo.getResultProjId()){
				throw new CustomException("结算项目不能为空！");
			}
		}
		Integer payType = bo.getPayType();
		//支付类别:0：支付报销，1：冲销借款，2：冲销预付
		if(payType == 0){

		}
		if(payType == 1 || payType == 3){
			if(null == bo.getLoanList() || bo.getLoanList().size() == 0){
				throw new CustomException("冲销借款,借款单据不能为空！");
			}
			this.dealSysLoan(bo);
		}
		if(payType == 2 || payType == 3){
			if(null == bo.getAdvanceList() || bo.getAdvanceList().size() == 0){
				throw new CustomException("冲销预付款,预付款单据不能为空！");
			}
			this.dealSysAdvance(bo);

		}
        SysReimbursement add = BeanUtil.toBean(bo, SysReimbursement.class);
        validEntityBeforeSave(add);
        return save(add);
    }



    @Override
    public Boolean updateByEditBo(SysReimbursementChargeBo bo) {
		Integer payType = bo.getPayType();
		//支付类别:0：支付报销，1：冲销借款，2：冲销预付
		if(payType == 0){

		}
		if(payType == 1|| payType == 3){
			if(null == bo.getLoanList() || bo.getLoanList().size() == 0){
				throw new CustomException("冲销借款,借款单据不能为空！");
			}
			this.dealSysLoan(bo);
		}
		if(payType == 2|| payType == 3){
			if(null == bo.getAdvanceList() || bo.getAdvanceList().size() == 0){
				throw new CustomException("冲销预付款,预付款单据不能为空！");
			}
			this.dealSysAdvance(bo);

		}
        SysReimbursement update = BeanUtil.toBean(bo, SysReimbursement.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

	@Override
	@Transactional
	public Boolean audit(BaseAuditBo bo) {
    	boolean rsp = false;
    	List<Long> idList = bo.getIdList();
		if(null == idList || idList.size() == 0){
			throw new CustomException("需审核的数据不能为空！");
		}
		for(Long id:idList){
			SysReimbursementVo sysReimbursementVo = this.queryById(id);
			// TODO 结账效验
			iSysCheckaccountService.check(sysReimbursementVo.getProjId(),sysReimbursementVo.getCreateTime());
			boolean auditStatus =  sysReimbursementVo.getAuditStatus();
			if(!auditStatus){
				//1、 更新报销单审核状态
				SysReimbursement sysReimbursement = new SysReimbursement();
				sysReimbursement.setId(sysReimbursementVo.getId());
				sysReimbursement.setAuditStatus(true);
				baseMapper.updateById(sysReimbursement);
				//2、审核冲销明细,并 更新借款、预付款单余额和冲销状态
				//支付类别:0：支付报销，1：冲销借款，2：冲销预付
				Integer payType = sysReimbursementVo.getPayType();
				if(payType == 0 || sysReimbursementVo.getReimbPayAmt().compareTo(new BigDecimal(0)) >0){
					SysFundaccountdetailAddBo addBo = new SysFundaccountdetailAddBo();
					addBo.setCategory(1L);
					addBo.setProjId(sysReimbursementVo.getProjId());
					addBo.setProjName(sysReimbursementVo.getProjName());
					addBo.setSubjectId(sysReimbursementVo.getBudgetId());
					addBo.setSubjectName(sysReimbursementVo.getBudgetName());
					addBo.setContractId(sysReimbursementVo.getContractId());
					addBo.setContractName(sysReimbursementVo.getContractName());
					addBo.setSettleProj(sysReimbursementVo.getResultProjId());
					addBo.setSettleProjName(sysReimbursementVo.getResultProjName());
					addBo.setAccId(sysReimbursementVo.getReimbPayAccountId());
					addBo.setAccountName(sysReimbursementVo.getReimbPayAccountName());
					addBo.setAccountBank(sysReimbursementVo.getReimbPayAccountBank());
					addBo.setAccountNo(sysReimbursementVo.getReimbPayAccountNo());
					addBo.setTransactionCategory(4L);
					addBo.setSenderId(sysReimbursementVo.getReimbPayAccountId());
					addBo.setSender(sysReimbursementVo.getReimbPayAccountName());
					addBo.setReceive(sysReimbursementVo.getAffiliatedPerson());
					addBo.setTransactionId(sysReimbursementVo.getReimbursementNo());
					addBo.setManagerId(sysReimbursementVo.getHandlerId());
					addBo.setManager(sysReimbursementVo.getHandler());
					addBo.setTransactionType(sysReimbursementVo.getReimbPayWay());
					addBo.setTransactionDate(sysReimbursementVo.getCreateTime());
					addBo.setAmount(sysReimbursementVo.getReimbPayAmt());
					addBo.setRemarks(sysReimbursementVo.getRemark());
					rsp = iSysFundaccountdetailService.insertByAddBo(addBo);
				}
				if(payType == 1 || payType == 3){
					List<SysLoanChargeBo> sysLoanChargeBoList = sysReimbursementVo.getLoanList();
					if(null == sysLoanChargeBoList || sysLoanChargeBoList.size() == 0){
						throw new CustomException("查询报销单，未查询该报销单借款冲销明细数据！");
					}
					List<String> resultContractNoList = sysLoanChargeBoList.stream().map(SysLoanChargeBo::getResultContractNo).collect(Collectors.toList());;
					SysLoanQueryBo sysLoanQueryBo = new SysLoanQueryBo();
					sysLoanQueryBo.setResultContractNoList(resultContractNoList);
					sysLoanQueryBo.setAuditStatus(true);
					sysLoanQueryBo.setWriteoffStatus(0);
					sysLoanQueryBo.setLoanType(0);
					List<SysLoanVo>  sysLoanVoList = sysLoanMapper.queryList(sysLoanQueryBo);
					if(null == sysLoanVoList || sysLoanVoList.size() == 0){
						throw new CustomException("冲销借款，未查询到借款单据数据！");
					}
					for(SysLoanChargeBo sysLoanChargeBo:sysLoanChargeBoList){
						String resultContractNo = sysLoanChargeBo.getResultContractNo();
						List<SysLoanVo> sysLoanVoFilter = sysLoanVoList.stream().filter(sysLoanVo->sysLoanVo.getResultContractNo().equals(resultContractNo)).collect(Collectors.toList());
						if(null == sysLoanVoFilter || sysLoanVoFilter.size() !=1){
							throw new CustomException("冲销借款，过滤借款单数据异常！");
						}


						//当前借款单的
						SysLoanVo sysLoanVo = sysLoanVoFilter.get(0);

						SysLoan sysLoan = new SysLoan();
						SysLoan sysLoanCharge = new SysLoan();
						sysLoan.setId(sysLoanVo.getId());
						sysLoanCharge.setId(sysLoanChargeBo.getId());
						BigDecimal amount = sysLoanChargeBo.getAmount();
						BigDecimal balance = sysLoanVo.getBalance();
						balance = balance.subtract(amount);

						if(balance.compareTo(new BigDecimal(0)) == -1){
							throw new CustomException("冲销借款，冲销金额"+amount+"大于可冲销金额"+balance);
						}
						if(balance.compareTo(new BigDecimal(0)) == 0){
							sysLoan.setWriteoffStatus(1);
						}
						if(balance.compareTo(new BigDecimal(0)) == 1){
							sysLoan.setWriteoffStatus(0);

						}
						sysLoan.setBalance(balance);
						sysLoan.setAuditStatus(true);
						sysLoanCharge.setAuditStatus(true);
						sysLoanMapper.updateById(sysLoan);
						rsp = sysLoanMapper.updateById(sysLoanCharge) > 0;
					}
				}
				if(payType == 2 || payType == 3){
					List<SysCreditAdvanceChargeBo>  advanceChargeBoList = sysReimbursementVo.getAdvanceList();
					if(null == advanceChargeBoList || advanceChargeBoList.size() == 0){
						throw new CustomException("查询报销单，未查询到该报销单预付冲销明细数据！");
					}
					List<String> advanceNoList = advanceChargeBoList.stream().map(SysCreditAdvanceChargeBo::getAdvanceNo).collect(Collectors.toList());;
					SysCreditAdvanceQueryBo sysCreditAdvanceQueryBo = new SysCreditAdvanceQueryBo();
					sysCreditAdvanceQueryBo.setAdvanceNoList(advanceNoList);
					sysCreditAdvanceQueryBo.setAuditStatus(true);
					sysCreditAdvanceQueryBo.setWriteoffStatus(0);
					sysCreditAdvanceQueryBo.setAdvanceType(0);
					List<SysCreditAdvanceVo>  sysCreditAdvanceVoList = sysCreditAdvanceMapper.queryList(sysCreditAdvanceQueryBo);
					if(null == sysCreditAdvanceVoList || sysCreditAdvanceVoList.size() == 0){
						throw new CustomException("冲销预付款，未查询到预付款单据数据！");
					}
					for(SysCreditAdvanceChargeBo sysCreditAdvanceChargeBo:advanceChargeBoList){
						String advanceNo = sysCreditAdvanceChargeBo.getAdvanceNo();
						List<SysCreditAdvanceVo> sysCreditAdvanceVoFilter = sysCreditAdvanceVoList.stream().filter(sysCreditAdvanceVo->sysCreditAdvanceVo.getAdvanceNo().equals(advanceNo)).collect(Collectors.toList());
						if(null == sysCreditAdvanceVoFilter || sysCreditAdvanceVoFilter.size() !=1){
							throw new CustomException("冲销预付款，过滤预付款单数据异常！");
						}

						//当前借款单的
						SysCreditAdvanceVo sysCreditAdvanceVo = sysCreditAdvanceVoFilter.get(0);

						SysCreditAdvance sysCreditAdvance = new SysCreditAdvance();
						SysCreditAdvance sysCreditAdvanceCharge = new SysCreditAdvance();
						sysCreditAdvance.setId(sysCreditAdvanceVo.getId());
						sysCreditAdvanceCharge.setId(sysCreditAdvanceChargeBo.getId());
						BigDecimal amount = sysCreditAdvanceChargeBo.getAdvanceAmt();
						BigDecimal balance = sysCreditAdvanceVo.getAdvanceBalance();
						balance = balance.subtract(amount);
						if(balance.compareTo(new BigDecimal(0)) == -1){
							throw new CustomException("冲销预付款，冲销金额"+amount+"大于可冲销金额"+balance);
						}
						if(balance.compareTo(new BigDecimal(0)) == 0){
							sysCreditAdvance.setWriteoffStatus(1);
						}
						if(balance.compareTo(new BigDecimal(0)) == 1){
							sysCreditAdvance.setWriteoffStatus(0);

						}

						sysCreditAdvance.setAdvanceBalance(balance);
						sysCreditAdvance.setAuditStatus(true);
						sysCreditAdvanceCharge.setAuditStatus(true);
						sysCreditAdvanceMapper.updateById(sysCreditAdvance);
						rsp = sysCreditAdvanceMapper.updateById(sysCreditAdvanceCharge) > 0;
					}

				}

			}
		}



    	return rsp;

	}

	private synchronized Boolean changeFundaccount(SysReimbursementEditBo bo){
    	//付类别:0：支付报销，1：冲销借款，2：冲销预付
		Integer payType = bo.getPayType();
		SysFundaccountdetailAddBo addBo = new SysFundaccountdetailAddBo();
		addBo.setCategory(1L);
		addBo.setProjId(bo.getProjId());
		addBo.setProjName(bo.getProjName());
		addBo.setSubjectId(bo.getBudgetId());
		addBo.setSubjectName(bo.getBudgetName());
		addBo.setContractId(bo.getContractId());
		addBo.setContractName(bo.getContractName());
		addBo.setSettleProj(bo.getResultProjId());
		addBo.setSettleProjName(bo.getResultProjName());

		addBo.setAccId(bo.getReimbPayAccountId());
		addBo.setAccountName(bo.getReimbPayAccountName());
		addBo.setAccountBank(bo.getReimbPayAccountBank());
		addBo.setAccountNo(bo.getReimbPayAccountNo());


		//支付报销
		//付类别:0：支付报销，1：冲销借款，2：冲销预付
		if(payType.equals(0)){
			addBo.setTransactionCategory(4L);
			addBo.setSenderId(bo.getReimbPayAccountId());
			addBo.setSender(bo.getReimbPayAccountName());
			addBo.setReceiveId(bo.getAffiliatedPersonId());
			addBo.setReceive(bo.getAffiliatedPerson());
			addBo.setTransactionId(bo.getReimbursementNo());
		}
		if(payType.equals(1)){
			addBo.setTransactionCategory(5L);
			addBo.setSenderId(bo.getReimbPayAccountId());
			addBo.setSender(bo.getReimbPayAccountName());
			addBo.setReceiveId(bo.getAffiliatedPersonId());
			addBo.setReceive(bo.getAffiliatedPerson());
			addBo.setTransactionId(bo.getReimbursementNo());
		}
		if(payType.equals(2)){
			addBo.setTransactionCategory(6L);
			addBo.setSenderId(bo.getReimbPayAccountId());
			addBo.setSender(bo.getReimbPayAccountName());
			addBo.setReceiveId(bo.getAffiliatedUnitId());
			addBo.setReceive(bo.getAffiliatedUnit());
			addBo.setTransactionId(bo.getReimbursementNo());
		}

		addBo.setManagerId(bo.getHandlerId());
		addBo.setManager(bo.getHandler());
		addBo.setTransactionType(bo.getReimbPayWay());
		addBo.setTransactionDate(bo.getCreateTime());
		addBo.setAmount(bo.getReimbAmt());
		addBo.setRemarks(bo.getRemark());
		return iSysFundaccountdetailService.insertByAddBo(addBo);


	}


	/**
	 * 新增/编辑 报销冲销时处理借款冲销明细信息
	 * @param bo
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	 private void dealSysLoan(SysReimbursementChargeBo bo){
		List<SysLoanChargeBo> sysLoanChargeBoList = bo.getLoanList();
		List<String> resultContractNoList = sysLoanChargeBoList.stream().map(SysLoanChargeBo::getResultContractNo).collect(Collectors.toList());
		SysLoanQueryBo sysLoanQueryBo = new SysLoanQueryBo();
		sysLoanQueryBo.setResultContractNoList(resultContractNoList);
		sysLoanQueryBo.setLoanType(0);
		 sysLoanQueryBo.setWriteoffStatus(0);
		sysLoanQueryBo.setAuditStatus(true);
		List<SysLoanVo> sysLoanVoList = iSysLoanService.queryList(sysLoanQueryBo);

		//需修改的借款单冲销明细
		List<SysLoan> sysLoanAddChargeList = new ArrayList<>();
		//循环借款单
		for(SysLoanVo sysLoanVo:sysLoanVoList){
			String resultContractNo = sysLoanVo.getResultContractNo();
			BigDecimal balance = sysLoanVo.getBalance();
			if(StringUtils.isBlank(resultContractNo)){
				throw new CustomException("报销时，在数据库中查询到的借款单编号为空！");
			}
			for(SysLoanChargeBo sysLoanChargeBo:bo.getLoanList()){
				String resultContractNoCharge = sysLoanChargeBo.getResultContractNo();
				if(StringUtils.isBlank(resultContractNo)){
					throw new CustomException("报销的借款单编号为空！");
				}
				//匹配需要冲销的借款单
				if(resultContractNo.equals(resultContractNoCharge)){
					BigDecimal amount = sysLoanChargeBo.getAmount();
					if(amount.compareTo(new BigDecimal(0)) >= 0){
						SysLoan sysLoanAddCharge = BeanUtil.toBean(sysLoanVo, SysLoan.class);
						sysLoanAddCharge.setId(null);
						sysLoanAddCharge.setAmount(amount);
						sysLoanAddCharge.setBalance(new BigDecimal(0));
						sysLoanAddCharge.setResultContractNo(sysLoanVo.getResultContractNo());
						sysLoanAddCharge.setResultContractNoCharge(bo.getReimbursementNo());
						sysLoanAddCharge.setLoanType(2);
						sysLoanAddCharge.setAbstracted("个人借款冲销");
						sysLoanAddCharge.setHandlerId(bo.getHandlerId());
						sysLoanAddCharge.setHandler(bo.getHandler());
						sysLoanAddCharge.setCreateTime(bo.getCreateTime());
						sysLoanAddCharge.setImage("");
						sysLoanAddCharge.setRemark("个人借款冲销");
						sysLoanAddCharge.setAuditStatus(false);
						sysLoanAddChargeList.add(sysLoanAddCharge);

					}



				}
			}
		}

		if(sysLoanAddChargeList.size() == 0){
			throw new CustomException("冲销借款,至少冲销一条借款单！");
		}

		//重新新增借款单冲销信息
		if(sysLoanAddChargeList.size() > 0){
			//删除现有冲销记录
			HashMap delParams = new HashMap();
			delParams.put("result_contract_no_charge",bo.getReimbursementNo());
			sysLoanMapper.deleteByMap(delParams);
			for(SysLoan in:sysLoanAddChargeList){
				iSysLoanService.save(in);
			}
//			sysLoanMapper.insertAll(sysLoanAddChargeList);
		}



	}


	private void dealSysAdvance(SysReimbursementChargeBo bo){
		List<SysCreditAdvanceChargeBo> sysAdvanceChargeBoList = bo.getAdvanceList();
		List<String> advanceNoList = sysAdvanceChargeBoList.stream().map(SysCreditAdvanceChargeBo::getAdvanceNo).collect(Collectors.toList());
		SysCreditAdvanceQueryBo sysCreditAdvanceQueryBo = new SysCreditAdvanceQueryBo();
		sysCreditAdvanceQueryBo.setAdvanceType(0);
		sysCreditAdvanceQueryBo.setWriteoffStatus(0);
		sysCreditAdvanceQueryBo.setAdvanceNoList(advanceNoList);
		sysCreditAdvanceQueryBo.setAuditStatus(true);
		List<SysCreditAdvanceVo> sysCreditAdvanceVoList = sysCreditAdvanceMapper.queryList(sysCreditAdvanceQueryBo);

		//需修改的借款单冲销明细
		List<SysCreditAdvance> sysCreditAdvanceAddChargeList = new ArrayList<>();
		//循环借款单
		for(SysCreditAdvanceVo sysCreditAdvanceVo:sysCreditAdvanceVoList){
			String advanceNo = sysCreditAdvanceVo.getAdvanceNo();
			BigDecimal balance = sysCreditAdvanceVo.getAdvanceBalance();
			if(StringUtils.isBlank(advanceNo)){
				throw new CustomException("报销时，在数据库中查询到的预付款单编号为空！");
			}
			for(SysCreditAdvanceChargeBo sysCreditAdvanceChargeBo:bo.getAdvanceList()){
				String advanceNoCharge = sysCreditAdvanceChargeBo.getAdvanceNo();
				if(StringUtils.isBlank(advanceNo)){
					throw new CustomException("报销的借款单编号为空！");
				}
				//匹配需要冲销的借款单
				if(advanceNo.equals(advanceNoCharge)){
					BigDecimal amount = sysCreditAdvanceChargeBo.getAdvanceAmt();
					if(amount.compareTo(new BigDecimal(0)) >= 0){
						SysCreditAdvance sysCreditAdvanceAddCharge = BeanUtil.toBean(sysCreditAdvanceVo, SysCreditAdvance.class);
						sysCreditAdvanceAddCharge.setId(null);
						sysCreditAdvanceAddCharge.setAdvanceAmt(amount);
						sysCreditAdvanceAddCharge.setAdvanceBalance(new BigDecimal(0));
						sysCreditAdvanceAddCharge.setAdvanceNo(sysCreditAdvanceVo.getAdvanceNo());
						sysCreditAdvanceAddCharge.setAdvanceNoCharge(bo.getReimbursementNo());
						sysCreditAdvanceAddCharge.setAdvanceType(2);
						sysCreditAdvanceAddCharge.setHandlerId(bo.getHandlerId());
						sysCreditAdvanceAddCharge.setHandler(bo.getHandler());
						sysCreditAdvanceAddCharge.setCreateTime(bo.getCreateTime());
						sysCreditAdvanceAddCharge.setImage("");
						sysCreditAdvanceAddCharge.setRemark("预付款冲销");
						sysCreditAdvanceAddCharge.setAuditStatus(false);
						sysCreditAdvanceAddChargeList.add(sysCreditAdvanceAddCharge);

					}



				}
			}
		}

		if(sysCreditAdvanceAddChargeList.size() == 0){
			throw new CustomException("冲销预付款,至少冲销一条预付款单！");
		}

		//重新新增借款单冲销信息
		if(sysCreditAdvanceAddChargeList.size() > 0){
			//删除现有冲销记录
			HashMap delParams = new HashMap();
			delParams.put("advance_no_charge",bo.getReimbursementNo());
			sysCreditAdvanceMapper.deleteByMap(delParams);
			for(SysCreditAdvance in:sysCreditAdvanceAddChargeList){
				iSysCreditAdvanceService.save(in);
			}
//			sysCreditAdvanceMapper.insertAll(sysCreditAdvanceAddChargeList);
		}



	}
	/**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SysReimbursement entity){
        //TODO 做一些数据校验,如唯一约束
		// TODO 结账效验
		iSysCheckaccountService.check(entity.getProjId(),entity.getCreateTime());
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }
}
